package com.hkts.naturalgas.tcp;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hkts.naturalgas.dictionaries.utils.DBUtils;
import com.hkts.naturalgas.summary.entity.SummaryDictionary;
import com.hkts.naturalgas.summary.mapper.SummaryDictionaryMapper;
import com.hkts.naturalgas.summary.service.ISummaryDictionaryService;
import com.hkts.naturalgas.summary.service.serviceimpl.SummaryDictionaryServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassNameTcpServerHandler
 * @Description
 * @Author yck
 * @Date2021-12-03 10:13
 * @Version V1.0
 **/
@Slf4j
public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private ISummaryDictionaryService summaryDictionaryMapper=new SummaryDictionaryServiceImpl();


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        log.info(msg.toString());
        String s = msg.toString();
        if(s.contains(SummaryConstance.BEGIN_FLAG)){
            String[] split = s.split(SummaryConstance.BEGIN_FLAG);
            for(int i=0;i<split.length;i++){
                //包含开头和结尾则进行数据处理
                if(split[i].contains(SummaryConstance.MINUTE_DATA_FLAG)&&split[i].contains(SummaryConstance.END_FLAG)){
                    handlerData(split[i]);
                //包含开头不包含结尾需要处理拆包，放入全局常量等待处理
                }else if(split[i].contains(SummaryConstance.MINUTE_DATA_FLAG)&&!split[i].contains(SummaryConstance.END_FLAG)){
                    SummaryConstance.CACHE_DATA=split[i];
                }
            }

        }else{
            if(StringUtils.isNotBlank(SummaryConstance.CACHE_DATA)){
                s= SummaryConstance.CACHE_DATA+s;
                SummaryConstance.CACHE_DATA="";
                handlerData(s);
            }

        }
    }
    public void handlerData(String msg){
        String[] split = msg.toString().split(";");
        String mn = "";
        String time = "";
        String so2 = "";
        String nox = "";
        String cn = "";
        String wasteGas = "";
        String smoke = "";
        for (int i = 0; i < split.length; i++) {
            if(split[i].contains(SummaryConstance.CN)){
                cn = StrUtils.splitMN(split[i]);
            }else if (split[i].contains(SummaryConstance.MN)) {
                mn = StrUtils.splitMN(split[i]);
            } else if (split[i].contains(SummaryConstance.DataTime)) {
                time = StrUtils.splitDataTime(split[i]);
            } else if (split[i].contains(SummaryConstance.a21026_Cou)) {
                so2 = StrUtils.splitSo2orNox(split[i], SummaryConstance.a21026_Cou);
            } else if (split[i].contains(SummaryConstance.a21002_Cou)) {
                nox = StrUtils.splitSo2orNox(split[i], SummaryConstance.a21002_Cou);
            }else if(split[i].contains(SummaryConstance.a00000_Cou)){
                wasteGas = StrUtils.splitSo2orNox(split[i], SummaryConstance.a00000_Cou);
            }else if(split[i].contains(SummaryConstance.a34013_Cou)){
                smoke= StrUtils.splitSo2orNox(split[i], SummaryConstance.a34013_Cou);
            }
        }
        if (cn.equals(SummaryConstance.MINUTE_DATA)) {
            QueryWrapper<SummaryDictionary> query = Wrappers.query();
            query.lambda().eq(SummaryDictionary::getMn, mn);
            ISummaryDictionaryService summaryDictionaryMapper= SpringContextHolder.getBean(SummaryDictionaryServiceImpl.class);
            SummaryDictionary summaryDictionary = summaryDictionaryMapper.getOne(query);
            log.info(summaryDictionary.toString());
            DBUtils dBUtils= SpringContextHolder.getBean(DBUtils.class);
            int summaryCountByTime = dBUtils.getSummaryCountByTime(summaryDictionary, time);
            if(summaryCountByTime==0){
                String summaryInsertSql = dBUtils.getSummaryInsertSql(summaryDictionary, time, so2, nox,wasteGas,smoke);
                log.info("汇总数据插入sql:{}", summaryInsertSql);
                List<String> sqlList = new ArrayList<>();
                sqlList.add(summaryInsertSql);
                dBUtils.updateBatch(sqlList);
            }
        }
    }
    /**
     * @param ctx 上下文
     * @param evt 事件
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {

            //将  evt 向下转型 IdleStateEvent
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            switch (event.state()) {
                case READER_IDLE:
                    handlerReaderIdle(ctx);
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    handlerWriterIdle(ctx);
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    handlerAllIdle(ctx);
                    eventType = "读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + "--超时时间--" + eventType);
            System.out.println("服务器做相应处理..");

            //如果发生空闲，我们关闭通道
            // ctx.channel().close();
        }
    }

    protected void handlerAllIdle(ChannelHandlerContext ctx) {
        System.err.println("---ALL_IDLE---");
    }

    protected void handlerWriterIdle(ChannelHandlerContext ctx) {
        System.err.println("---WRITER_IDLE---");
    }


    protected void handlerReaderIdle(ChannelHandlerContext ctx) {
        System.err.println("---READER_IDLE---");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.add(ctx.channel());


    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        System.err.println(" ---" + ctx.channel().remoteAddress() + "----- is  inAction");
        channelGroup.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //链接异常情况处理
        cause.printStackTrace();
        channelGroup.remove(ctx.channel());
        ctx.channel().close();
        log.info(cause.getMessage());
    }
}
